package com.xyzh.stj.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyzh.stj.web.dto.user.QueryUserPageDTO;
import com.xyzh.stj.web.entity.*;
import com.xyzh.stj.web.dao.UserInfoMapper;
import com.xyzh.stj.web.service.*;
import com.xyzh.stj.web.vo.user.UserDetials;
import com.xyzh.stj.web.vo.user.UserInfo;
import com.xyzh.stj.web.vo.user.UserOrganizationVo;
import com.xyzh.application.base.service.BasicServiceImpl;
import com.xyzh.application.base.vo.AuthorUser;
import com.xyzh.application.common.constants.ReqPage;
import com.xyzh.application.common.util.ResultHelper;
import com.xyzh.application.common.util.SecurityUtils;
import com.xyzh.application.config.security.Md5Encode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author @JZB
 * @since 2023-10-29
 */
@Service
public class UserInfoServiceImpl extends BasicServiceImpl<UserInfoMapper, UserEntity> implements UserInfoService {
    @Autowired
    private RoleService roleService;

    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private RightService rightService;

    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private UserOrganizationService userOrganizationService;

    @Value("#{applicationProperies.info.adminCode}")
    private String sysAdmin;


    @Override
    public UserInfo getCurrentUser() {
        UserInfo userInfo = new UserInfo();
        AuthorUser user = SecurityUtils.getAuthorUser();
        if (sysAdmin.equals(user.getUsername())) {
            UserEntity entity = this.getBaseMapper().selectById(user.getId());
            entity.setPassword(null);
            BeanUtils.copyProperties(entity, userInfo);
            userInfo.setRights(rightService.getAllRight(new RightEntity()));
            userInfo.setApplications(applicationService.getAllList());
        } else {
            String userid = this.getLocalUserId();
            if (StrUtil.isEmpty(userid)) {
                return null;
            }
            UserEntity entity = this.getBaseMapper().selectById(userid);
            entity.setPassword(null);
            BeanUtils.copyProperties(entity, userInfo);
            List<RoleEntity> roles = roleService.getRoleByUserid(userid);
            userInfo.setRole(roles);
            List<OrganizationEntity> organizationEntities = organizationService.getOrganizations(userid);
            userInfo.setOrganization(organizationEntities);
            userInfo.setRights(rightService.getRightsByUser(roles, organizationEntities));
            userInfo.setApplications(applicationService.getUserApplications());
        }
        return userInfo;

    }


    @Override
    public boolean saveEntity(UserEntity userEntity) {

        userEntity.setPassword(Md5Encode.encode(userEntity.getPassword()));
        if (0 == userEntity.getEnabled()) {
            userEntity.setEnabled(1);
        }
        return super.saveEntity(userEntity);
    }

    @Override
    public boolean updateEntity(UserEntity entity) {
        if (StrUtil.isNotEmpty(entity.getPassword())) {
            entity.setPassword(Md5Encode.encode(entity.getPassword()));
        }
        return super.updateEntity(entity);
    }

    @Override
    public List<UserEntity> list(UserEntity userEntity) {
        List<UserEntity> lists = super.list(userEntity);
        lists.stream().forEach(d -> {
            d.setPassword(null);
        });
        return lists;
    }

    @Override
    public boolean save(UserEntity entity) {
        entity.setPassword(Md5Encode.encode(entity.getPassword()));
        if (0 == entity.getEnabled()) {
            entity.setEnabled(1);
        }
        return super.save(entity);
    }

    @Override
    public boolean deleteEntity(UserEntity entity) {
        //删除用户角色
        UserRoleEntity userRoleEntity = new UserRoleEntity();
        userRoleEntity.setUserId(entity.getId());
        userRoleService.deleteEntityNotId(userRoleEntity);
        //删除机构用户
        UserOrganizationEntity userOrganizationEntity = new UserOrganizationEntity();
        userOrganizationEntity.setUserid(entity.getId());
        userOrganizationService.deleteEntityNotId(userOrganizationEntity);


        return super.deleteEntity(entity);
    }

    @Override
    public ResultHelper queryByPage(ReqPage<UserEntity> reqPage) {
        ResultHelper resultHelper = super.queryByPage(reqPage);
        Page<UserEntity> page = (Page<UserEntity>) resultHelper.getData();
        page.getRecords().stream().forEach(d -> d.setPassword(null));
        return resultHelper;
    }

    @Override
    public ResultHelper queryLikeByPage(ReqPage<UserEntity> reqPage) {
        ResultHelper resultHelper = super.queryLikeByPage(reqPage);
        Page<UserEntity> page = (Page<UserEntity>) resultHelper.getData();
        page.getRecords().stream().forEach(d -> d.setPassword(null));
        return resultHelper;
    }

    @Override
    public List<UserOrganizationVo> getUserLitsByParentOrganizationid(String organizationid) {
        List<UserOrganizationVo> list = this.getBaseMapper().getUserLitsByParentOrganizationid(organizationid);
        list.stream().forEach(d -> {
            d.setPassword(null);
        });
        return list;
    }

    @Override
    public IPage<UserOrganizationVo> queryUserPage(QueryUserPageDTO query, long currentPage, long size) {
        List<UserOrganizationVo> list = new ArrayList<>();
        long totalRecord = 0L;
        List<UserOrganizationEntity> userOrgans=userOrganizationService.list(new UserOrganizationEntity());
        List<OrganizationEntity> organizationEntities=organizationService.list(new OrganizationEntity());

        list = this.getBaseMapper().queryUserList(query, (currentPage - 1) * size, size);
        list.stream().forEach(d -> {
            d.setPassword(null);
            List<String> orgs=userOrgans.stream().map(t->{
                if(d.getId().equals(t.getUserid())){
                    return t.getOrganizationid();
                }
                return null;
            }).collect(Collectors.toList());
            List<OrganizationEntity> organs=organizationEntities.stream().filter(it->orgs.contains(it.getId())).collect(Collectors.toList());
            d.setOrgname(organs.stream().map(its->{return  its.getName();}).collect(Collectors.joining(",")));
            d.setOrgid(organs.stream().map(its->{return  its.getId();}).collect(Collectors.joining(",")));
        });
        totalRecord = this.getBaseMapper().queryTotalList(query);

        Page<UserOrganizationVo> page = new Page<>();
        page.setRecords(list);
        page.setTotal(totalRecord);
        page.setSize(size);
        page.setPages(currentPage);
        return page;
    }

    @Override
    public UserDetials queryUserDetials(String userid) {

        UserEntity user = this.getById(userid);
        UserDetials userDetials = new UserDetials();
        BeanUtils.copyProperties(user, userDetials);
        userDetials.setPassword(null);
        UserRoleEntity queryRole = new UserRoleEntity();
        queryRole.setUserId(userDetials.getId());
        List<UserRoleEntity> userRoleEntities = userRoleService.list(queryRole);
        userDetials.setAuthorityInfo(userRoleEntities.stream().map(d -> {
            return d.getRoleId();
        }).collect(Collectors.toList()));
        UserOrganizationEntity queryOrg = new UserOrganizationEntity();
        queryOrg.setUserid(userDetials.getId());
        List<UserOrganizationEntity> userOrganizationEntities = userOrganizationService.list(queryOrg);
        userDetials.setAccountDepartmentInfo(userOrganizationEntities.stream().map(d -> {
            return d.getOrganizationid();
        }).collect(Collectors.toList()));
        return userDetials;

    }

    @Override
    public Boolean resetPassword(String userId) {
        UserEntity userEntity = this.selectById(userId);
        userEntity.setPassword(Md5Encode.encode("1234abcd@2023"));
//        userEntity.setUpdateby(this.getLocalUserId());
//        userEntity.setUpdatetime(new Date());
        return this.updateEntity(userEntity);
    }

}
